package com.example.rmation.controller;

import com.example.rmation.model.entity.User;
import com.example.rmation.service.UserService;
import com.example.rmation.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RequestMapping("/api/user")
@RestController
public class LoginController {

    @Autowired
    UserService userService;

    @PostMapping("/studentLogin")
    public Result studentLogin(@RequestBody User user, HttpSession session) {
        String account = user.getAccount();
        String password = user.getPassword();
        //1.判断username password 是否为空
        if (StringUtils.isEmpty(account)){ //StringUtils.isEmpty()判断是否为 null值和字符空
            return Result.error("account为空");
        }
        if (StringUtils.isEmpty(password)){
            return Result.error("password为空");
        }

        User users = userService.login(account,password);
        if ( users.getAccountStatus() == 0) {
            return Result.error(5000,"账号停用!无法登录");
        }
        if (!users.getRole().equals(1)) {
            return Result.error(5000,"您不是学生!无法登录");
        }
        System.out.println(users);
        //保存用户信息时，不报存密码
        users.setPassword(null);
        //将用户信息存入到session中
        session.setAttribute("user",users);
        return Result.success(user);
    }

    @PostMapping("/teacherLogin")
    public Result teacherLogin(@RequestBody User user, HttpSession session) {
        String account = user.getAccount();
        String password = user.getPassword();
        System.out.println(account+"    "+password);

        //1.判断username password 是否为空
        if (StringUtils.isEmpty(account)){ //StringUtils.isEmpty()判断是否为 null值和字符空
            return Result.error("account为空");
        }
        if (StringUtils.isEmpty(password)){
            return Result.error("password为空");
        }
        User users = userService.login(account,password);
        if ( users.getAccountStatus() == 0) {
            return Result.error(5000,"账号停用!无法登录");
        }
        if (!users.getRole().equals(2)) {
            return Result.error(5000,"您不是教师!无法登录");
        }
        System.out.println(users);
        //保存用户信息时，不报存密码
        users.setPassword(null);
        //将用户信息存入到session中
        session.setAttribute("user",users);
        return Result.success(user);
    }

    /**
     * 登出 释放session
     */
    @GetMapping ("/logout")
    @ResponseBody
    public Result logout(HttpSession session){
        //根据key值 释放session
        session.removeAttribute("user");
        return Result.success();
    }
}
